<template>
	<div>
		<el-form :disabled="isDisabled" class="dialog-layout" ref="userForm" :rules="rules" :model="state.ruleForm" size="default" label-width="120px">
			<el-row :gutter="35">
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
					<div class="title-info">子系统基本信息</div>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
					<el-button size="default" type="success" @click="state.dialogVisible = true"> 请选择子系统信息 </el-button>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" prop>
					<el-form-item label="子系统ID">
						<el-input :disabled="true" v-model="state.selectedRow.id" placeholder="请选择子系统信息" clearable></el-input>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" prop>
					<el-form-item label="系统名称">
						<el-input :disabled="true" v-model="state.selectedRow.name" placeholder="请选择子系统信息" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
					<el-form-item label="授权状态">
						<el-select :disabled="true" v-model="state.selectedRow.isAuthorization" placeholder="请选择子系统信息" class="w100">
							<el-option label="已授权" :value="true" />
							<el-option label="未授权" :value="false" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
					<el-form-item label="授权类型">
						<el-select :disabled="true" v-model="state.selectedRow.authorizationType" multiple placeholder="请选择子系统信息" class="w100">
							<el-option label="查询数据" value="1" />
							<el-option label="修改数据" value="2" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" prop>
					<el-form-item label="授权用户" prop="userIds">
						<el-select size="default" v-model="state.ruleForm.userIds" multiple placeholder="授权用户" class="w100">
							<el-option v-for="item in state.userData" :key="item.ID" :label="item.UserName" :value="item.ID" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
					<el-form-item label="查询时段" prop="dateArr">
						<el-time-picker
							v-model="state.ruleForm.dateArr"
							is-range
							range-separator="至"
							start-placeholder="开始时间"
							value-format="HH:mm:ss"
							end-placeholder="结束时间"
							align="right"
						/>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20"> <div class="title-info">子系统接入接口及数据配置</div> </el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
					<el-button size="default" type="success" @click="addSub"> 新增 </el-button>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
					<el-table ref="productTable" :data="state.ruleForm.fieldConfigs" border class="attribute-table">
						<el-table-column prop="date" label="接口" min-width="100" align="center">
							<template #default="scope">
								<el-select
									size="default"
									v-model="scope.row.salesNum"
									@change="getFunctionData(scope.row, scope.$index, false)"
									placeholder="请选择接口"
								>
									<el-option v-for="item in state.functionList" :key="item.id" :label="item.functionDisplayName" :value="item.id" />
								</el-select>
							</template>
						</el-table-column>
						<el-table-column prop="date" label="数据" min-width="100" align="center">
							<template #default="scope">
								<div class="date" v-if="scope.row.salesNum">
									<div class="date-item" v-for="(item, index) in scope.row.list" :key="index">
										{{ item.functionDisplayName }}
									</div>
								</div>
							</template>
						</el-table-column>
						<el-table-column prop="date" label="查询修改" min-width="50" align="center">
							<template #default="scope">
								<div class="date" v-if="scope.row.salesNum">
									<div class="date-item" v-for="(item, index) in scope.row.list" :key="index">
										<el-checkbox v-model="item.canModifys"></el-checkbox>
									</div>
								</div>
							</template>
						</el-table-column>
						<el-table-column prop="date" label="过期时间" min-width="100" align="center">
							<template #default="scope">
								<div class="date" v-if="scope.row.salesNum">
									<div class="date-item" v-for="(item, index) in scope.row.list" :key="index">
										<el-date-picker
											value-format="YYYY-MM-DD HH:mm:ss"
											v-model="item.expirationDate"
											type="datetime"
											:disabled-date="item.disabledDate"
											placeholder="选择日期"
										></el-date-picker>
									</div>
								</div>
							</template>
						</el-table-column>
						<el-table-column prop="date" label="操作" width="80" align="center">
							<template #default="scope">
								<el-button type="danger" circle size="small" @click="del(scope.$index)">
									<el-icon>
										<ele-Delete />
									</el-icon>
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
			</el-row>
		</el-form>
		<div class="dialog-btn">
			<el-button @click="onCancel" size="default">取 消</el-button>
			<el-button :disabled="isDisabled" type="primary" @click="onSubmit(userForm)" size="default">确 认</el-button>
		</div>
		<!-- 弹窗 -->
		<el-dialog
			title="请选择子系统数据"
			v-model="state.dialogVisible"
			:close-on-click-modal="false"
			:show-close="false"
			:close-on-press-escape="false"
			width="1000px"
		>
			<subLisyTem @onSubmitSub="onSubmitSub" @closeSub="closeSub" />
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, defineAsyncComponent } from 'vue';
import { GrantSubSystemInfoCreate, GrantSubSystemInfoUpdate } from '/@/api/subSystemPower/index';
import { UserGetPagedList } from '/@/api/userInformation/index';
import { SubSystemInfoId } from '/@/api/subSystemInfo/index';
import { FunctionInfoGetPagedList } from '/@/api/Interface/index';
import { FormInstance, ElMessage } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
// 引入组件
const subLisyTem = defineAsyncComponent(() => import('./subLisyTem.vue'));
// 定义父组件传过来的值
const props = defineProps({
	editItem: {
		type: Object,
		default: () => {},
	},
	isDisabled: {
		type: Boolean,
		default: false,
	},
});
// 定义子组件向父组件传值/事件
const emit = defineEmits(['close']);

// 定义变量内容
const state = reactive({
	ruleForm: {
		subSystemId: '', // 子系统ID
		userIds: '', //用户id
		dateArr: [] as any,
		fieldConfigs: [] as any,
	} as any,
	num: 0,
	userData: [] as any[], // 用户数据
	functionList: [] as any[], // 接口
	dialogVisible: false, // 弹窗状态
	selectedRow: {} as any,
});

onMounted(() => {
	getTableData();
});

const getTableData = async () => {
	const params = {
		PageIndex: 1,
		PageSize: 999999,
	};
	let dataUser = await UserGetPagedList(params);
	let dataFun = await FunctionInfoGetPagedList(params);
	state.userData = dataUser.data.items;
	state.functionList = dataFun.data.items;
	if (Object.keys(props.editItem).length) {
		for (const key in state.ruleForm) {
			if (props.editItem[key]) state.ruleForm[key] = props.editItem[key];
		}
		state.ruleForm.dateArr = [props.editItem.startTime, props.editItem.endTime];
		if (typeof props.editItem.userIds === 'string' && props.editItem.userIds.includes(',')) {
			state.ruleForm.userIds = props.editItem.userIds.split(',');
		} else {
			state.ruleForm.userIds = [props.editItem.userIds];
		}
		let detailsArr = props.editItem.interfaces;

		if (detailsArr.length) {
			detailsArr.map((v: any, n: any) => {
				state.ruleForm.fieldConfigs.push({
					salesNum: v.functionId,
				});
				getFunctionData(v, n, true);
			});
		}
		let dataInfo = await SubSystemInfoId(props.editItem.subSystemId);
		onSubmitSub(dataInfo.data);
	}
};

// 增加
const addSub = () => {
	state.ruleForm.fieldConfigs.push({});
};
// 删除数据
const del = (key: any) => {
	state.ruleForm.fieldConfigs.splice(key, 1);
};
// 选择数据
const getFunctionData = (key: any, num: any, isEdid: Boolean) => {
	const selectedFunction: any | undefined = isEdid
		? state.functionList.find((item) => item.id === key.functionId)
		: state.functionList.find((item) => item.id === key.salesNum);

	state.ruleForm.fieldConfigs[num].list = selectedFunction.fields;
	state.ruleForm.fieldConfigs[num].isModify = selectedFunction.isModify;
	state.ruleForm.fieldConfigs[num].id = selectedFunction.id;

	const disabledDate = (data: any) => {
		const today = new Date();
		today.setHours(0, 0, 0, 0);
		return data.getTime() < today.getTime();
	};
	state.ruleForm.fieldConfigs[num].list.forEach((v: any) => {
		v.expirationDate = `${formatDate(new Date(), 'YYYY-mm-dd')} 23:59:59`;
		v.canModifys = false;
		v.disabledDate = disabledDate;
	});
	if (isEdid) {
		key.fieldConfigs.forEach((d: any) => {
			state.ruleForm.fieldConfigs[num].list.forEach((v: any) => {
				if (d.functionId == v.id) {
					v.expirationDate = d.expirationDate;
					v.canModifys = true;
					v.disabledDate = disabledDate;
					v.editId = d.id;
				}
			});
		});
	}
	console.log(selectedFunction);

	return selectedFunction ? selectedFunction.fields : [];
};
// 关闭弹窗
const onCancel = () => {
	emit('close');
};
// 关闭选择弹窗
const closeSub = () => {
	state.dialogVisible = false;
};
// 选择数据
const onSubmitSub = (v: any) => {
	state.selectedRow = v;
	state.ruleForm.subSystemId = v.id;
	if (typeof v.authorizationType === 'string' && v.authorizationType.includes(',')) {
		v.authorizationType = v.authorizationType.split(',');
	} else {
		v.authorizationType = [v.authorizationType];
	}

	state.dialogVisible = false;
};

const rules = reactive({
	userIds: [{ required: true, message: '请选择授权用户', trigger: ['blur', 'change'] }],
	dateArr: [{ required: true, message: '请选择时间', trigger: ['blur', 'change'] }],
});
const userForm = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	if (!state.ruleForm.subSystemId) return ElMessage.warning('请选择子系统信息');

	if (!state.ruleForm.fieldConfigs.length) return ElMessage.warning('请新增子系统接入接口及数据配置');
	await formEl.validate(async (valid) => {
		if (valid) {
			const params = {
				...state.ruleForm,
				interfaces: [],
			};
			if (state.ruleForm.fieldConfigs.length) {
				state.ruleForm.fieldConfigs.map((v: any) => {
					v.selectList = v.list.filter((item: any) => item.canModifys === true);

					if (v.selectList && v.selectList.length) {
						v.selectList.map((k: any) => {
							(k.functionId = k.id), (k.parentFunctionId = k.pid);
							k.canModify = v.isModify == 0 ? false : true;
							if (k.editId) {
								k.id = k.editId;
							} else {
								delete k.id;
							}
						});
						params.interfaces.push({
							functionId: v.id,
							subSystemId: state.selectedRow.id,
							canModify: v.isModify == 0 ? false : true,
							fieldConfigs: v.selectList,
						});
					}
				});
			}
			params.userIds = params.userIds.join(',');
			delete params.fieldConfigs;
			if (Array.isArray(state.ruleForm.dateArr) && state.ruleForm.dateArr.length > 0) {
				params.startTime = state.ruleForm.dateArr[0];
				params.endTime = state.ruleForm.dateArr[1];
				delete params.dateArr;
			}
			if (Object.keys(props.editItem).length) {
				await GrantSubSystemInfoUpdate(params, props.editItem.id);
			} else {
				await GrantSubSystemInfoCreate(params);
			}
			ElMessage.success(Object.keys(props.editItem).length ? '修改成功' : '新增成功');
			onCancel();
		}
	});
};
</script>

<style scoped lang="scss">
.title-info {
	font-size: 16px;
	color: #000;
	position: relative;
	&::before {
		content: '';
		position: absolute;
		left: -5px;
		top: 50%;
		transform: translateY(-50%);
		width: 2px;
		height: 14px;
		background: var(--next-bg-menuBar);
	}
}
:deep(.el-dialog__body) {
	max-height: calc(90vh - 80px) !important;
}
.date {
	.date-item {
		height: 50px;
		line-height: 50px;
	}
}
</style>
